package com.evan.kdl.test.day01;

import com.evan.kdl.util.CommonUtils;

import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author huangzhongliang
 * @time 2024/01/04 16:14
 * 编排2个依赖关系的异步任务 thenCompose()
 */
public class ThenComposeDemo2 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CommonUtils.printThreadLog("main start");
        ExecutorService executor = Executors.newFixedThreadPool(4);
        CompletableFuture<String[]> filterWordFuture = CompletableFuture.supplyAsync(() -> {
            CommonUtils.printThreadLog("读取filter_words文件");
            String s = CommonUtils.readFile("F:\\idea-workspace-personal\\juc-springboot-demo\\src\\main\\resources\\filter_words.txt");
            return s;
        }).thenComposeAsync(c ->
                //耗时
                CompletableFuture.supplyAsync(() -> {
                    CommonUtils.printThreadLog("把内容转换成敏感词数组");
                    return c.split(",");
                }, executor));

        String[] filterWords = filterWordFuture.get();
        //要关闭不然一直在等异步任务
        executor.shutdown();
        CommonUtils.printThreadLog("filterWords = " + Arrays.toString(filterWords));
        CommonUtils.printThreadLog("main end");
    }
}
